package com.shycloud.mido.opter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.pay.alipay.utils.AliPayUtil;
import com.shycloud.mido.opter.api.dto.BelongDto;
import com.shycloud.mido.opter.api.dto.OptInfoDTO;
import com.shycloud.mido.opter.api.dto.OptSearchDTO;
import com.shycloud.mido.opter.api.dto.SysUserDto;
import com.shycloud.mido.opter.api.entity.MemberActivate;
import com.shycloud.mido.opter.api.entity.OptOperator;
import com.shycloud.mido.opter.api.entity.OptReGiveVip;
import com.shycloud.mido.opter.api.entity.OrgSettledCount;
import com.shycloud.mido.opter.api.feign.RemoteMemberService;
import com.shycloud.mido.opter.api.feign.RemoteSysUserService;
import com.shycloud.mido.opter.api.vo.OptHardwareVO;
import com.shycloud.mido.opter.api.vo.OptOperatorVO;
import com.shycloud.mido.opter.api.vo.ReGiveVipVO;
import com.shycloud.mido.opter.mapper.MemberActivateMapper;
import com.shycloud.mido.opter.mapper.NewOperatorMapper;
import com.shycloud.mido.opter.service.NewOperatorService;
import com.shycloud.mido.opter.service.OptReGiveVipService;
import com.shycloud.mido.opter.service.OrgSettledCountService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.*;

@RestController
@AllArgsConstructor
@RequestMapping("/new_manage")
public class NewOperatorController {

	/** 运营商业务 mapper */
	private NewOperatorMapper optMapper;
	/** 激活硬件业务 mapper */
	private MemberActivateMapper memberActivateMapper;
	/** 运营商业务 service */
	private NewOperatorService newOperatorService;
	/** 七牛云上传 */
	private MinioTemplate minioTemplate;
	/** feign 系统用户模块 */
	private RemoteSysUserService remoteSysUserService;
	/** feign app用户模块 */
	private RemoteMemberService remoteMemberService;
	/** 运营商续费 VIP 业务 service */
	private OptReGiveVipService optReGiveVipService;
	/** 结算业务 service */
	private OrgSettledCountService settledCountService;
	/** 密码加密工具类 */
	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	@GetMapping("getOptById")
	public R getOptById(Integer optId) {
		return new R(optMapper.selectById(optId));
	}

	/**
	 * 新增运营商
	 *
	 * @param opt
	 * @return
	 * @author nianhua.jiang
	 * @date 2021/4/8 10:22
	 **/
	@Transactional
	@ApiOperation("新增运营商")
	@PostMapping("/add")
	public R add(@RequestBody OptOperator opt) {
		// 远程调用查找sysUserId
		Integer sysUserId =
				(Integer) remoteSysUserService.getSysUserIdByName(opt.getPhone()).getData();
		if (sysUserId == 0) {
			// 1. 是否有用户 没有则创建
			SysUserDto user = new SysUserDto();
			user.setUsername(opt.getPhone());
			String pwdStr = ENCODER.encode("123456");
			user.setPassword(pwdStr);
			optMapper.createSysUser(user);
			sysUserId = Integer.parseInt(user.getId());
		}
		try {
			// 2. 有用户没有权限则加权限
			optMapper.createSysUserRole(sysUserId.toString());
		} catch (Exception e) {
			// 3. 有用户有权限则报错提示已有运营商
			return new R<>(1, "该手机号已创建过运营商, 请重试", false);
		}
		//市级运营商判断
		if (opt.getRank().equals("0")) {
			// 判断是否存在省级运营商
//			QueryWrapper provinceWrapper = new QueryWrapper<>();
//			provinceWrapper.eq("city", opt.getCity());
//			if (optMapper.selectList(provinceWrapper).size() > 0 && opt.getRank().equals("0")) {
//				throw new BusinessException("该地区已有运营商，无法新增运营商");
//			}
		}

		// TODO: 暂时取消独家运营商的判定
		// if (opt.getRank().equals("1")) {
		// //判断此区域是否有三个运营商
		// QueryWrapper provinceWrapper = new QueryWrapper<>();
		// provinceWrapper.eq("province", opt.getProvince());
		// if (optMapper.selectList(provinceWrapper).size() >= 3 && opt.getRank().equals("1")) {
		// throw new BusinessException("该省已有三家运营商，无法新增运营商");
		// }
		// //判断是否有独家运营商
		// QueryWrapper proAloneWrapper = new QueryWrapper<>();
		// proAloneWrapper.eq("province", opt.getProvince());
		// proAloneWrapper.eq("is_alone", 1);
		// if (optMapper.selectList(proAloneWrapper).size() > 0) {
		// throw new BusinessException("该区域已签署1个独家运营商，无法新增运营商");
		// }
		// }
		// if (opt.getRank().equals("0")) {
		// QueryWrapper cityWrapper = new QueryWrapper<>();
		// cityWrapper.eq("city", opt.getCity());
		// if (optMapper.selectList(cityWrapper).size() >= 3 && opt.getRank().equals("0")) {
		// throw new BusinessException("该省已有三家运营商，无法新增运营商");
		// }
		// QueryWrapper cityAloneWrapper = new QueryWrapper<>();
		// cityAloneWrapper.eq("city", opt.getCity());
		// cityAloneWrapper.eq("is_alone", 1);
		// if (optMapper.selectList(cityAloneWrapper).size() > 0) {
		// throw new BusinessException("该区域已签署1个独家运营商，无法新增运营商");
		// }
		// }
		optMapper.insert(opt);
		// 如果没有支付宝账号则不生成图片&&不绑定分账关系
		if (StringUtils.isNotBlank(opt.getAlipay())
				&& StringUtils.isNotBlank(opt.getAlipayName())) {
			if (!AliPayUtil.AliRelationBind(opt.getAlipay(), opt.getAlipayName(),
					opt.getId().toString())) {
				throw new BusinessException("绑定分账关系失败, 请重新核对支付宝账户与实名认证信息");
			}
			String qrcodeUrl = this.getH5Comb(opt.getId().toString(), opt.getName(), opt.getContact());
			opt.setQrcodeUrl(qrcodeUrl);
			optMapper.updateById(opt);
		}
		return new R<>(true);
	}

	// public static void main(String[] args) {
	// try {
	// //Win路径
	// BufferedImage big = ImageIO.read(new File("D:/back.png"));
	// BufferedImage small = createImage("http://192.168.0.148:8080?optId="+1);
	// Graphics2D g = big.createGraphics();
	//
	// //二维码或小图在大图的左上角坐标
	// int x = (big.getWidth()-small.getWidth())/2;
	// int y = 2295;
	// Font font1 = new Font("宋体 常规", Font.BOLD, 132);
	// Font font2 = new Font("宋体 常规", Font.BOLD, 108);
	// g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
	// g.setColor(Color.WHITE);
	// g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	// String line1 = "佳音教育机构";
	// String line2 = "13274341499";
	// g.setFont(font1);
	// g.drawString(line1, (big.getWidth()-getWordWidth(font1, line1))/2, (3840+132));
	// g.setFont(font2);
	// g.drawString(line2, (big.getWidth()-getWordWidth(font2, line2))/2, (4026+108));
	// g.dispose();
	// //为了保证大图背景不变色，formatName必须为"png"
	// File f = File.createTempFile("tmp-", ".png"); // 提供临时文件的前缀和后缀
	// f.deleteOnExit();
	// ImageIO.write(big, "png", f);
	// //写文件到本地
	// ImageIO.write(big, "png", new File("C:/Users/ondor/Desktop/combinePic.png"));
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

	public String getH5Comb(String optId, String line1, String line2) {
		try {
			// Linux路径
			BufferedImage big = ImageIO.read(new File("/var/shycloud-opter-biz/back.png"));
			BufferedImage small = createImage("http://shop.joymido.com?optId=" + optId);
			Graphics2D g = big.createGraphics();

			// 二维码或小图在大图的左上角坐标
			int x = (big.getWidth() - small.getWidth()) / 2;
			int y = 2295;
			Font font1 = new Font("宋体", Font.BOLD, 132);
			Font font2 = new Font("宋体", Font.BOLD, 108);
			g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
			g.setColor(Color.WHITE);
			g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
					RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			g.setFont(font1);
			g.drawString(line1, (big.getWidth() - getWordWidth(font1, line1)) / 2, (3840 + 132));
			g.setFont(font1);
			g.drawString(line2, (big.getWidth() - getWordWidth(font2, line2)) / 2, (4026 + 108));
			g.dispose();
			// 为了保证大图背景不变色，formatName必须为"png"
			File f = File.createTempFile("tmp-", ".png"); // 提供临时文件的前缀和后缀
			f.deleteOnExit();
			ImageIO.write(big, "png", f);
			return minioTemplate.uploadFile(new FileInputStream(f), "shop_" + optId + ".png",
					"zebra-attachment");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	// 求字符串的宽度(用于居中显示)
	public static int getWordWidth(Font font, String content) {
		FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
		int width = 0;
		for (int i = 0; i < content.length(); i++) {
			width += metrics.charWidth(content.charAt(i));
		}
		return width;
	}

	private static BufferedImage createImage(String content) throws IOException, WriterException {
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, 2);
		// 200是定义的二维码或小图片的大小
		BitMatrix bitMatrix =
				new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 1200, 1200, hints);
		int width = bitMatrix.getWidth();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 循环遍历每一个像素点
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
			}
		}
		// 本地路径
		// BufferedImage logo = ImageIO.read(new File("D:/logo.png"));
		// 服务器路径
		BufferedImage logo = ImageIO.read(new File("/var/shycloud-opter-biz/logo.png"));
		Graphics2D g = image.createGraphics();
		int x = (1200 - logo.getWidth() * 2) / 2;
		int y = (1200 - logo.getHeight() * 2) / 2;
		g.drawImage(logo, x, y, logo.getWidth() * 2, logo.getHeight() * 2, null);

		return image;
	}

	@PostMapping("/update")
	public R update(@RequestBody OptOperator opt) {
		OptOperator oldOpt = optMapper.selectById(opt.getId());
		// 如果账户的支付宝账号为空则直接进行绑定
		if (oldOpt.getAlipay() == null || oldOpt.getAlipayName() == null) {
//			if (!AliPayUtil.AliRelationBind(opt.getAlipay(), opt.getAlipayName(),
//					opt.getId().toString())) {
//				throw new BusinessException("绑定分账关系失败, 请重新核对支付宝账户与实名认证信息");
//			}
		} else {
			// 如果账户发生变化则重新绑定分账关系
			if (!oldOpt.getAlipay().equals(opt.getAlipay())
					|| !oldOpt.getAlipayName().equals(opt.getAlipayName())) {
//				if (!AliPayUtil.AliRelationUnBind(oldOpt.getAlipay(), oldOpt.getAlipayName(),
//						oldOpt.getId().toString())) {
//					throw new BusinessException("解除分账关系绑定失败, 请重试");
//				}
//				if (!AliPayUtil.AliRelationBind(opt.getAlipay(), opt.getAlipayName(),
//						opt.getId().toString())) {
//					throw new BusinessException("绑定分账关系失败, 请重新核对支付宝账户与实名认证信息");
//				}
			}
		}
		// 如果没有二维码图片则生成新图片
		if (!StringUtils.isNotBlank(oldOpt.getQrcodeUrl())) {
			String optName = opt.getName();
			String contact = opt.getContact();
			if (StringUtils.isBlank(optName)) {
				optName = oldOpt.getName();
			}
			if (StringUtils.isBlank(contact)) {
				contact = oldOpt.getContact();
			}
			String qrcodeUrl = this.getH5Comb(opt.getId().toString(), optName, contact);
			opt.setQrcodeUrl(qrcodeUrl);
		}

		if (opt.getUnPreStorageCount() != null) {
			opt.setUnPreStorageCount(oldOpt.getUnPreStorageCount() - opt.getUnPreStorageCount());
		}

		return new R<>(optMapper.updateById(opt));
	}

	@GetMapping("/getNumberByProvince")
	public R getNumberByProvince(String province) {
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("province", province);
		return new R<>(optMapper.selectList(queryWrapper).size());
	}

	@GetMapping("/getNumberByCity")
	public R getNumberByCity(String city) {
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("city", city);
		return new R<>(optMapper.selectList(queryWrapper).size());
	}

	@GetMapping("/page")
	public R page(Page<OptOperatorVO> page, OptSearchDTO opt) {
		// 省级
		if (opt.getRank().equals("1")) {
			IPage<OptOperatorVO> result = optMapper.getProvincePage(page, opt);
			for (OptOperatorVO item : result.getRecords()) {
				QueryWrapper queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("parent", item.getId());
				item.setExpandCount(optMapper.selectList(queryWrapper).size());
			}
			return new R<>(result);
		}
		// 市级
		else {
			IPage<OptOperatorVO> result = optMapper.getCityPage(page, opt);
			return new R<>(result);
		}
	}

	@PostMapping("/belong")
	public R belong(@RequestBody BelongDto dto) {

		// 省级运营商
		if (dto.getRank() == 1) {
			// 先清除原有的归属关系
			optMapper.cancelBelongToOpt(dto.getTargetId());
			if (dto.getIds().size() == 0) {
				return new R<>();
			} else {
				return new R<>(optMapper.belongTo(dto.getTargetId(), dto.getIds()));
			}
		}
		// 市级运营商
		else {
			optMapper.cancelBelongToOrg(dto.getTargetId());
			if (dto.getIds().size() == 0) {
				return new R<>();
			} else {
				// 先解除掉归属的总部的机构
				optMapper.cancelBelongToHeadquarters(dto.getIds());
				return new R<>(optMapper.belongToOrg(dto.getTargetId(), dto.getIds()));
			}
		}

	}

	@GetMapping("/getBelongRelationship")
	public R getBelongRelationship(Integer rank, Integer id) {
		// 省运营商返回市运营商列表
		if (rank == 1) {
			return new R<>(optMapper.getProvinceBelong(id));
		}
		// 市运营商返回机构列表
		else {
			return new R<>(optMapper.getCityBelong(id));
		}
	}

	@GetMapping("/getNoBelongRelationship")
	public R getNoBelongRelationship(Integer rank, Integer id, String name) {

		// 如果是省运营商查找id对应的省
		// 根据省来查找list
		if (rank == 1) {
			OptOperator opt = optMapper.selectById(id);
			String province = opt.getProvince();
			return new R<>(optMapper.getProvinceNoBelong(province));
		}
		// 市同理
		else {
			//if (id == 999999) {
			return new R<>(optMapper.getCityNoBelong(null, name));
			//}
			//String city = optMapper.getOptCityById(id);
			//return new R<>(optMapper.getCityNoBelong(city, name));
		}

	}

	// Added

	/**
	 * 运营商根据时长获取存货随机激活码
	 *
	 * @param duration 时长
	 * @param optId    运营商id
	 * @return
	 */
	@GetMapping("/getRandomStockCode")
	@ApiOperation("根据时长获取存货随机激活码")
	public R getRandomStockCode(Integer duration, String optId, String orgId) {
		QueryWrapper wrapper = new QueryWrapper<MemberActivate>();
		if (optId != null) {
			wrapper.eq("optr_id", optId);
		} else if (orgId != null) {
			wrapper.eq("org_id", orgId);
		}
		wrapper.isNull("member_id");
		if (duration != null) {
			wrapper.eq("duration", duration);
		}
		List<MemberActivate> actvlist = memberActivateMapper.selectList(wrapper);

		return actvlist.size() == 0 ? new R<>(CommonConstants.FAIL, "未找到运营商库存激活码", false)
				: new R<>(actvlist.get(new Random().nextInt(actvlist.size())).getActvCode());
	}

	/**
	 * 上传附件
	 *
	 * @param files
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/09/29 14:29
	 */
	@ApiOperation("上传附件")
	@PostMapping("/uploadAttachment")
	public R uploadRecord(@RequestParam(value = "files") List<MultipartFile> files) {

		List<String> resultUrl = new ArrayList<>();

		try {
			for (MultipartFile file : files) {
				String url = minioTemplate.uploadFile(file.getInputStream(),
						file.getOriginalFilename(), "zebra-attachment");
				resultUrl.add(url);
			}
		} catch (IOException e) {
			return new R(CommonConstants.FAIL, e.getLocalizedMessage(), false);
		}
		return new R(resultUrl);
	}

	@ApiOperation("上传微信图片")
	@PostMapping("/wxQrcodeUrl")
	public R wxQrcodeUrl(@RequestParam(value = "files") List<MultipartFile> files) {

		List<String> resultUrl = new ArrayList<>();

		try {
			for (MultipartFile file : files) {
				String url = minioTemplate.uploadFile(file.getInputStream(),
						file.getOriginalFilename(), "zebra-attachment");
				resultUrl.add(url);
			}
		} catch (IOException e) {
			return new R(CommonConstants.FAIL, e.getLocalizedMessage(), false);
		}
		return new R(resultUrl);
	}

	/**
	 * 运营商分页获取教师审核信息
	 *
	 * @param current
	 * @param size
	 * @param name
	 * @param status  1->已审核
	 * @param optrId  运营商id
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/19 17:57
	 */
	@GetMapping("/page_approval")
	@ApiOperation("/运营商分页获取教师审核信息")
	public R getTeacherApprovalPage(Integer current, Integer size, String name, String status,
									String optrId) {
		// 分页参数
		Page page = new Page(current, size);
		return new R<>(newOperatorService.getTeacherApprovalPage(page, name, status, optrId));
	}

	@GetMapping("/getProvinceNoBelongByNameOrPhone")
	public R getNoBelongRelationshipByNameOrPhone(Integer rank, String keyWord) {
		if (rank == 1) {
			return new R<>(optMapper.getProvinceNoBelongByNameOrPhone(keyWord));
		} else {
			return new R<>(optMapper.getCityNoBelongByNameOrPhone(keyWord));
		}
	}

	/**
	 * 获取运营商，机构列表
	 *
	 * @param type        0-市运营商 1-省运营商 2-机构工作室
	 * @param nameOrPhone 客户名称或电话号
	 * @param current     当前页
	 * @param size        每页显示条数
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/9/25 16:11
	 **/
	@GetMapping("getOptAndOrgList")
	public R getOptAndOrgList(String type, String nameOrPhone, Integer current, Integer size) {
		return new R(
				newOperatorService.getOptAndOrgList(type, nameOrPhone, new Page(current, size)));
	}

	@GetMapping("hardwareDueExperience")
	public R hardwareDueExperience() {
		return new R();
	}

	@GetMapping("hardwareDueOpened")
	public R hardwareDueOpened() {
		return new R();
	}

	@GetMapping("moreInfo")
	public R moreInfo(String optId) {
		Map<String, String> result = new HashMap<>();
		result.put("memberNumber", optMapper.getOptMemberNumber(optId));
		result.put("orgNumber", optMapper.getOptOrgNumber(optId));
		return new R(result);
	}

	@GetMapping("getProCityOrgStatistics")
	public R getProCityOrgStatistics(Integer optId) {
		Map<String, String> result = new HashMap<String, String>();
		// 没有optId的情况下为总部
		if (null == optId) {
			result.put("provinceOptNumber", optMapper.getProvinceOptNumber());
			result.put("cityOptNumber", optMapper.getCityOptNumber());
		} else {
			result.put("provinceOptNumber", "0");
			result.put("cityOptNumber", optMapper.getCityOptNumberByParentId(optId));
		}
		return new R(result);
	}

	@GetMapping("getOptBaseInfo")
	public R getOptBaseInfo(Integer optId) {
		OptOperator opt = optMapper.selectById(optId);
		OptInfoDTO optDto = new OptInfoDTO();
		optDto.getOnlineCourseAvail();
		BeanUtils.copyProperties(opt, optDto);
		return new R(optDto);
	}

	@PostMapping("actvHardWare")
	@ApiOperation("运营商开通硬件")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "用户memberId", paramType = "query",
					dataType = "String"),
			@ApiImplicitParam(name = "udid", value = "硬件UDID", paramType = "query",
					dataType = "String"),
			@ApiImplicitParam(name = "duration", value = "vip及基础作业功能期限(传天数)", paramType = "query",
					dataType = "int"),
			@ApiImplicitParam(name = "actvCode", value = "激活码", paramType = "query",
					dataType = "String"),
			@ApiImplicitParam(name = "optId", value = "运营商ID", paramType = "query",
					dataType = "int")})
	public R<Boolean> actvHardWare(@RequestBody OptHardwareVO optHardwareVO) {
		return new R(newOperatorService.actvHardWare(optHardwareVO));
	}

	/**
	 * 运营商续费VIP
	 *
	 * @param reGiveVip
	 * @return com.shycloud.mido.common.core.util.R<java.lang.Boolean>
	 * @author nianhua.jiang
	 * @date 2021/4/8 10:18
	 **/
	@PostMapping("reGiveVip")
	@ApiOperation("运营商续费VIP")
	public R<Boolean> reGiveVip(@RequestBody ReGiveVipVO reGiveVip) {

		R res = remoteMemberService.reGiveVip(reGiveVip);

		if (res.getCode() == 0) {
			// 插入运营商记录表，记录运营商开通的信息
			OptReGiveVip optReGiveVip = new OptReGiveVip();

			BeanUtils.copyProperties(reGiveVip, optReGiveVip);

			optReGiveVip.setCreateTime(new Date());

			return new R(optReGiveVipService.save(optReGiveVip));
		} else {
			return res;
		}

	}

	@ApiOperation("获取运营商续费历史记录")
	@GetMapping("getReGiveVipList")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "current", value = "当前页", required = true, paramType = "query",
					dataType = "int"),
			@ApiImplicitParam(name = "size", value = "每页大小", required = true, paramType = "query",
					dataType = "int"),
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query",
					dataType = "int"),
			@ApiImplicitParam(name = "username", value = "用户名/账号", paramType = "query",
					dataType = "String"),
			@ApiImplicitParam(name = "optId", value = "运营商ID", required = true, paramType = "query",
					dataType = "int")})
	public R getReGiveVipList(Integer current, Integer size, Integer orgId, String username,
							  String optId) {
		return new R(optReGiveVipService.getReGiveVipList(new Page(current, size), orgId, username,
				optId));
	}

	/**
	 * @param province
	 * @param city
	 * @return
	 * @Description: getDetailByLocation
	 * @author baiqiang.
	 * @date 2021年6月29日 下午7:23:11
	 * @version V1.0
	 */
	@ApiOperation("通过位置获取机构信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "province", value = "省份名称", required = true,
					paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "city", value = "城市名称", required = true, paramType = "query",
					dataType = "String")})
	@GetMapping("/getDetailByLocation")
	public R<List<OptOperator>> getDetailByLocation(String province, String city) {
		QueryWrapper<OptOperator> queryWrapper = new QueryWrapper<OptOperator>()
				.eq("province", province)
				.eq("city", city)
				.eq("status", "0")
				.orderByDesc("open_time");
		List<OptOperator> list = optMapper.selectList(queryWrapper);
		return new R(list);
	}

	@ApiOperation("通过位置获取机构信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "province", value = "省份名称", required = true,
					paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "city", value = "城市名称", required = true, paramType = "query",
					dataType = "String")})
	@GetMapping("/getDetailByLocationNonNull")
	public R<List<OptOperator>> getDetailByLocationNonNull(String province, String city) {
		QueryWrapper<OptOperator> queryWrapper = new QueryWrapper<OptOperator>()
				.eq("province", province)
				.eq("city", city)
				.eq("status", "0")
				.orderByDesc("open_time");
		List<OptOperator> list = optMapper.selectList(queryWrapper);
		if (CollectionUtils.isEmpty(list)) {
			QueryWrapper<OptOperator> queryNonNullWrapper = new QueryWrapper<OptOperator>()
					.eq("id", 38);
			list = optMapper.selectList(queryNonNullWrapper);
		}
		return new R(list);
	}

	/**
	 * 小程序后台管理 - 销售统计 - 获取代理商下的机构列表
	 *
	 * @param orgId 合作商 ID
	 * @return {@link R}
	 * @author nianhua.jiang
	 * @date 2022/1/6 13:18
	 */
	@GetMapping("getSaleOrgList")
	public R getSaleOrgList(Integer orgId, Integer optId) {
		return new R(newOperatorService.getSaleOrgList(orgId, optId));
	}

	/**
	 * 检查登录机构是否同时也是代理商
	 *
	 * @param orgId 机构ID
	 * @return {@link R}
	 * @author nianhua.jiang
	 * @date 2022/1/7 14:38
	 */
	@GetMapping("checkOrgIsOpt")
	public R checkOrgIsOpt(Integer orgId) {
		String phone = optMapper.getOrgPhoneByOrgId(orgId);
		List<OptOperator> opts = optMapper.selectList(new QueryWrapper<OptOperator>()
				.eq("phone", phone)
				.eq("status", "0"));
		Map<String, String> resMap = new HashMap<>(2);
		if (opts.size() > 0) {
			resMap.put("isOpt", "1");
			resMap.put("optId", opts.get(0).getId().toString());
		} else {
			resMap.put("isOpt", "0");
		}
		return new R(resMap);
	}

	/**
	 * 小程序端结算订单
	 *
	 * @param settledCount 结算订单信息
	 * @return {@link R}
	 * @author nianhua.jiang
	 * @date 2022/1/7 14:37
	 */
	@PostMapping("settledOrder")
	public R settledOrder(@RequestBody OrgSettledCount settledCount) {
		settledCount.setCreateTime(LocalDateTime.now());
		return new R(settledCountService.save(settledCount));
	}

}
